package com.epfresh.supplier.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.epfresh.api.entity.RequestEntityMap;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.global.BaseActivity;
import com.epfresh.api.global.BaseApplication;
import com.epfresh.api.http.HttpRequest;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.universalimageloader.core.ImageLoader;
import com.epfresh.api.utils.FormatUtil;
import com.epfresh.api.utils.JsonUtils;
import com.epfresh.api.utils.LocalDisplay;
import com.epfresh.supplier.R;
import com.epfresh.supplier.constant.Constant;
import com.epfresh.supplier.dialog.GrouponEnsureOrderDialog;
import com.epfresh.supplier.entity.AgencyListItem;
import com.epfresh.supplier.entity.BaseProductAreaConfigPrices;
import com.epfresh.supplier.entity.BaseStoreInfo;
import com.epfresh.supplier.entity.BuyerProduct;
import com.epfresh.supplier.entity.GrouponInfo;
import com.epfresh.supplier.entity.GrouponList;
import com.epfresh.supplier.entity.GrouponListItem;
import com.epfresh.supplier.entity.PayPreInfo;
import com.epfresh.supplier.view.tag.FlowLayout;
import com.epfresh.supplier.view.tag.TagAdapter;
import com.epfresh.supplier.view.tag.TagFlowLayout;
import com.epfresh.supplier.wxapi.WXPayEntryActivity;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

public class GrouponInfoActivity extends BaseActivity {


    String grouponId;
    String grouponIdOriginal;
    String productId;
    GrouponInfo mGrouponInfo;
    GrouponList mGrouponList;

    AgencyListItem agencyListItem;


    ImageView ivProduct;
    TextView tvStoreName;
    TextView tvProductTitle;
    TextView tvProductPrice;
    TextView tvProductPackage;
    TextView tvProductAlreadySize;
    TextView tvProductSize;
    TextView tvDeposit;
    TextView tvDeliveryDate;
    TextView tvSelectAgent;
    TextView tvSelectAgentName;
    TextView tvSelectAgentAddress;
    ImageView tvSelectAgentMap;
    TextView tvSelectStoreName;
    TextView tvExceptDate;
    TextView tvExceptTime;
    TextView tvAmountUnit;
    TextView tvTotalCost;
    TextView tvFreightCost;
    EditText etAmount;
    View vBottom;
    View vRecommend;
    View vRecommendBtn;
    TagFlowLayout mTflBuyerPrice;
    ImageView ivArrow;
    ImageView ivAgentArrow;
    List<BaseProductAreaConfigPrices> mPriceList = new ArrayList<>();
    List<BaseProductAreaConfigPrices> mPriceListAll = new ArrayList<>();
    TagAdapter<BaseProductAreaConfigPrices> mPriceAdapter;

    boolean isSingle;

    ViewHolder vhItem0;
    ViewHolder vhItem1;
    ViewHolder vhItem2;
    private String storeId;//基地店铺id
    private String zanting;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (savedInstanceState != null) {
            getIntent().putExtra(Constant.TYPE, savedInstanceState.getInt(Constant.TYPE));
            getIntent().putExtra("productId", savedInstanceState.getString("productId"));
            getIntent().putExtra("grouponId", savedInstanceState.getString("grouponId"));
            getIntent().putExtra("agencyItem", savedInstanceState.getString("agencyItem"));
            getIntent().putExtra("isSingle", savedInstanceState.getBoolean("isSingle"));

        }
        storeId = getIntent().getStringExtra("storeId");
        isSingle = getIntent().getBooleanExtra("isSingle", false);
        grouponId = getIntent().getStringExtra("grouponId");
        grouponIdOriginal = grouponId;
        productId = getIntent().getStringExtra("productId");
        String ais = getIntent().getStringExtra("agencyItem");
        zanting = getIntent().getStringExtra("zanting");
        updateAgencyData(ais);


        setContentView(R.layout.item_groupon_info);
        initView();
        reqGroupon(grouponId, productId);
//        if (grouponId != null)
    }

    private void updateAgencyData(String ais) {
        if (ais != null) {
            agencyListItem = JsonUtils.fromJson(ais, AgencyListItem.class);
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {

        outState.putString("grouponId", grouponIdOriginal);
        outState.putString("productId", productId);
        outState.putString("agencyItem", getIntent().getStringExtra("agencyItem"));
        outState.putBoolean("isSingle", getIntent().getBooleanExtra("isSingle", false));

        super.onSaveInstanceState(outState);
    }

    private void initView() {

        setToolbarTitle("拼货信息");

        findViewById(R.id.tv_bottom_btn_buyer).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                openDialog();
            }
        });

        tvTotalCost = (TextView) findViewById(R.id.tv_total_cost);
        tvFreightCost = (TextView) findViewById(R.id.tv_freight_cost);

        initTop();

        vhItem0 = new ViewHolder(findViewById(R.id.v_item_0));
        vhItem1 = new ViewHolder(findViewById(R.id.v_item_1));
        vhItem2 = new ViewHolder(findViewById(R.id.v_item_2));


        vhItem0.ivSelect.setTag(R.id.item_key_id, 0);
        vhItem1.ivSelect.setTag(R.id.item_key_id, 1);
        vhItem2.ivSelect.setTag(R.id.item_key_id, 2);

        vhItem0.ivSelect.setOnClickListener(onIvSelectedListener);
        vhItem1.ivSelect.setOnClickListener(onIvSelectedListener);
        vhItem2.ivSelect.setOnClickListener(onIvSelectedListener);


        updateGroupInfo();

    }

    View.OnClickListener onIvSelectedListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Object tag = v.getTag();
            Object p = v.getTag(R.id.item_key_id);
            if (p != null && p instanceof Integer && tag != null && tag instanceof GrouponListItem) {
                GrouponListItem data = (GrouponListItem) tag;

                int position = (int) p;

                boolean select = data.isSelected();
                if (select) {
                    data.setSelected(false);
                    updateData(null);
                } else {
                    data.setSelected(true);
                    updateData(data.getGrouponId());
                    String storeName = null;

                    if (agencyListItem == null)
                        agencyListItem = new AgencyListItem();
                    agencyListItem.setName(data.getAgencyStoreName());
                    agencyListItem.setConsigneeAddress(data.getAgencyConsigneeAddress());
                    agencyListItem.setConsigneeName(data.getAgencyConsigneeName());
                    agencyListItem.setConsigneePhone(data.getAgencyConsigneePhone());
                    agencyListItem.setId(data.getAgencyStoreId());

                    grouponId = data.getGrouponId();
                    updateAgency(agencyListItem);
                    mGrouponInfo.updateDeliveryDate(data.getDeliverTime1());
                    tvExceptDate.setText(mGrouponInfo.getDeliveryDate());
                }


                updateReCommendItem(grouponListCurrent);

            }
        }
    };
    public String grouponIdSelected;

    public void updateData(String id) {
        if (mGrouponList == null) {
            return;
        }
        List<?> items = mGrouponList.getGrouponList();
        boolean isSelectedGroup = false;
        if (items != null) {
            int size = items.size();
            for (int i = 0; i < size; i++) {
                Object o = items.get(i);
                if (o != null && o instanceof GrouponListItem) {
                    GrouponListItem gli = (GrouponListItem) o;

                    if (id != null && id.equals(gli.getGrouponId())) {
                        gli.setSelected(true);
                        isSelectedGroup = true;
                        grouponIdSelected = id;
                    } else {
                        gli.setSelected(false);
                    }
                }
            }
        }
        if (!isSelectedGroup) {
            grouponIdSelected = null;
        }
    }

    private void initTop() {

        tvStoreName = (TextView) findViewById(R.id.tv_store_title);
        ivProduct = (ImageView) findViewById(R.id.iv_product);
        tvProductTitle = (TextView) findViewById(R.id.tv_product_title);
        tvProductPrice = (TextView) findViewById(R.id.tv_product_price);
        tvProductPackage = (TextView) findViewById(R.id.tv_product_package);
        tvProductAlreadySize = (TextView) findViewById(R.id.tv_product_already_size);
        tvProductSize = (TextView) findViewById(R.id.tv_product_size);
        tvDeposit = (TextView) findViewById(R.id.tv_deposit);
        mTflBuyerPrice = (TagFlowLayout) findViewById(R.id.tfl_buyer_price);
        ivArrow = (ImageView) findViewById(R.id.iv_product_bottom_arrow);
        ivAgentArrow = (ImageView) findViewById(R.id.iv_agent_arrow);
        tvDeliveryDate = (TextView) findViewById(R.id.tv_delivery_date);
        tvSelectAgent = (TextView) findViewById(R.id.tv_select_angent);

        tvSelectAgentName = (TextView) findViewById(R.id.tv_select_angent_name);
        tvSelectAgentAddress = (TextView) findViewById(R.id.tv_select_address);
        tvSelectAgentMap = (ImageView) findViewById(R.id.iv_select_agent_map);
        tvSelectStoreName = (TextView) findViewById(R.id.tv_select_store_name);
        tvAmountUnit = (TextView) findViewById(R.id.tv_buy_amount_unit);
        etAmount = (EditText) findViewById(R.id.et_amount);
        tvExceptDate = (TextView) findViewById(R.id.tv_expect_date);
        tvExceptTime = (TextView) findViewById(R.id.tv_except_time);
        vBottom = findViewById(R.id.v_bottom_bg);
        vRecommend = findViewById(R.id.rl_commend);
        vRecommendBtn = findViewById(R.id.tv_recommend_btn);

        ivArrow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ivArrow.getVisibility() == View.VISIBLE) {
                    expendPrice();
                }
            }
        });

        vRecommendBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mGrouponInfo != null && mGrouponList != null) {
                    updateGroupInfo();
                }
            }
        });

        tvExceptTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                intoDate(mGrouponInfo);
            }
        });

        tvSelectAgent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                intoAgent(mGrouponInfo);
            }
        });
    }

    private void updateRecommendBtn(boolean isVisible) {


        vRecommendBtn.setVisibility(isVisible ? View.VISIBLE : View.GONE);
    }

    private void expendPrice() {

        if (mPriceList.size() > 3) {
            updatePriceList(false);
        } else {
            updatePriceList(true);
        }

        mPriceAdapter.notifyDataChanged();

    }

    private void updatePriceList(boolean isExpend) {
        mPriceList.clear();
        int size = mPriceListAll.size();
        if (size < 3) {
            ivArrow.setVisibility(View.INVISIBLE);
        }
        if (!isExpend) {
            ivArrow.setImageResource(R.mipmap.icon_base_product_up_arrow);
            size = size > 3 ? 3 : size;
        } else {
            ivArrow.setImageResource(R.mipmap.icon_base_product_down_arrow);
        }
        for (int i = 0; i < size; i++) {
            mPriceList.add(mPriceListAll.get(i));
        }
    }

    public void updateRecommendView(boolean isRecommend) {

        if (vBottom != null && vRecommend != null) {
            if (isRecommend) {
                vBottom.setVisibility(View.GONE);
                vRecommend.setVisibility(View.VISIBLE);
            } else {
                vRecommend.setVisibility(View.GONE);
                vBottom.setVisibility(View.VISIBLE);

            }
        }
    }

    void setData(GrouponInfo post) {
        if (isSingle) {
            ivAgentArrow.setVisibility(View.INVISIBLE);
            tvSelectAgent.setClickable(false);
        } else {
            ivAgentArrow.setVisibility(View.VISIBLE);
        }

        BuyerProduct p = post.getProduct();
        BaseStoreInfo baseStore = post.getBaseStore();


        String chargeUnit = "";
        if (p != null) {
            tvProductTitle.setText(p.getTitle());

            chargeUnit = p.getChargeUnit();
            if (baseStore != null) {
                tvStoreName.setText(baseStore.getName());
            } else {
                tvStoreName.setText("");
            }

            ImageLoader.getInstance().displayImage(p.getImgUrl(), ivProduct);

            tvProductPrice.setText(p.getPriceRangeStr());
//                定金30%  尾款70%
            String deposit = p.getDeposit();
            String depositLast = p.getDepositLast();


            deposit = "订金" + deposit + "%  尾款" + depositLast + "%";

            tvDeposit.setText(deposit);

            tvProductPackage.setText(p.getPack());

            String s = "满" + FormatUtil.subZeroAndDot(p.getMinOrderQuantity()) + chargeUnit + "发货，可拼" + FormatUtil.subZeroAndDot(p.getMaxOrderQuantity()) + chargeUnit;
            tvProductAlreadySize.setText(s);


          //  s = "已拼" + FormatUtil.subZeroAndDot(p.getSumProductCount()) + chargeUnit + "（还剩：" + FormatUtil.subZeroAndDot(FormatUtil.countAdd(p.getMaxOrderQuantity(), p.getSumProductCount())) + chargeUnit + "）";
            s = "已拼" + FormatUtil.subZeroAndDot(p.getCurProductCount()) + chargeUnit + "（还剩：" + FormatUtil.subZeroAndDot(p.getRemainProductCount()) + chargeUnit + "）";
            tvProductSize.setText(s);

            tvDeliveryDate.setText(post.getDeliveryInfo());
        }


        etAmount.setText(post.getProductCount());
        tvAmountUnit.setText(chargeUnit);
        tvExceptDate.setText(post.getDeliveryDate());

        etAmount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {

                mGrouponInfo.setProductCout(s.toString());

                updateBottomPrice();

            }
        });
        if (mPriceAdapter == null) {
            mPriceAdapter = new TagAdapter<BaseProductAreaConfigPrices>(mPriceList) {
                @Override
                public View getView(FlowLayout parent, int position, BaseProductAreaConfigPrices baseProductAreaConfigPrices) {
                    View v = LayoutInflater.from(GrouponInfoActivity.this).inflate(R.layout.tfl_item_product_price,
                            parent, false);
                    ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) v.getLayoutParams();
                    lp.width = (LocalDisplay.SCREEN_WIDTH_PIXELS - LocalDisplay.dp2px(24)) / 3;

                    TextView tvPrice = v.findViewById(R.id.tv_price);
                    TextView tvUnit = v.findViewById(R.id.tv_unit);
                    View vLine = v.findViewById(R.id.v_line);
                    String p = FormatUtil.subZeroAndDot(baseProductAreaConfigPrices.getPrice()) + "元/" + baseProductAreaConfigPrices.getChargeUnit();
                    tvPrice.setText(p);
                    tvUnit.setText(baseProductAreaConfigPrices.getOrderQuantityRange());
                    if (position == mPriceList.size() - 1 || position % 3 == 2) {
                        vLine.setVisibility(View.GONE);
                    } else {
                        vLine.setVisibility(View.VISIBLE);
                    }

                    return v;
                }
            };
            mPriceList.clear();
            mPriceListAll.clear();

            List<BaseProductAreaConfigPrices> prices = post.getPrices();
            if (prices != null) {
                for (int i = 0; i < prices.size(); i++) {
                    BaseProductAreaConfigPrices b = prices.get(i);
                    b.setChargeUnit(chargeUnit);
                    mPriceListAll.add(b);
                }
            }
            updatePriceList(false);
            mTflBuyerPrice.setAdapter(mPriceAdapter);


        }
    }



    void updatePrice(String s){

    }

    private void intoAgent(GrouponInfo data) {
        if (data == null) {
            return;
        }

        Intent intent = new Intent(this, AgencyListActivity.class);

        intent.putExtra("grouponId", grouponId);
        intent.putExtra("productId", productId);
        intent.putExtra("isFinish", true);
        startActivityForResult(intent, 0x1993);
    }

    private void intoDate(GrouponInfo data) {
        if (data == null) {
            return;
        }
        int index = data.getDeliveryListIndex();
        ArrayList<String> deliveryList = data.getDeliveryList();

        if (index > -1 && deliveryList.size() > 0 && index < deliveryList.size()) {
            Intent intent = new Intent(this, CalendarPreActivity.class);
            intent.putExtra("position", index);
            intent.putStringArrayListExtra("timeStringList", deliveryList);
            startActivityForResult(intent, 0x1991);
        }
    }

    GrouponEnsureOrderDialog dialog;

    public void openDialog() {

        String amount = etAmount.getText().toString();
        if (amount == null || mGrouponInfo == null) {
            return;
        }
        String maxProductCountLimited = mGrouponInfo.getMaxProductCountLimited();
        String minProductCountLimited = mGrouponInfo.getMinProductCountLimited();

        String chargeUnit = mGrouponInfo.getChargeUnit();
        if (FormatUtil.countAdd(maxProductCountLimited, amount, false) < 0) {
            toast("购买数量超出上限(" + FormatUtil.subZeroAndDot(maxProductCountLimited) + chargeUnit + ")");
            return;
        }
        if (FormatUtil.countAdd(amount, minProductCountLimited, false) < 0) {
            toast("购买数量低于起订量(" + FormatUtil.subZeroAndDot(minProductCountLimited) + chargeUnit + ")");
            return;
        }

        mGrouponInfo.setProductCout(amount);

        if (dialog == null) {
            dialog = new GrouponEnsureOrderDialog(this);
            dialog.setOnPayListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    reqGrouponSave();
                }
            });
        }
        dialog.show(mGrouponInfo);
    }

    private void intoPay(String requiredProductPayFirst
            , String payFirstCountDown
            , String orderId
    ) {
//        "requiredProductPayFirst" : 0.01,
//                "payFirstCountDown" : 1800,
//                "orderId" : 131


        if ("0".equals(FormatUtil.subZeroAndDot(requiredProductPayFirst))) {
            Intent success = new Intent(mContext, OrderOnGroupActivity.class);
            success.putExtra("orderType", 1);
            startActivity(success);

            finish();
            return;
        }
        Intent intent = new Intent(this, WXPayEntryActivity.class);

        intent.putExtra("requiredProductPayFirst", requiredProductPayFirst);//是否第一笔
        intent.putExtra("payFirstCountDown", payFirstCountDown);//倒计时
        intent.putExtra("orderId", orderId);
        //1订金 2尾款+运费
        intent.putExtra("receiptType", "1");
        startActivity(intent);
    }

    @Override
    public void onBackPressed() {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK && requestCode == 0x1991) {
            if (data != null && mGrouponInfo != null) {
                int position = data.getIntExtra("position", 0);
                String deliveryDate = mGrouponInfo.getDeliveryDate();
                mGrouponInfo.updateDeliveryDate(position);
                String deliveryDateNew = mGrouponInfo.getDeliveryDate();

                /*if (deliveryDateNew != null && deliveryDateNew.equals(deliveryDate)) {
                    grouponId = null;
                    updateData(null);
                    updateReCommendItem(grouponListCurrent);
                } else {
                }*/
                tvExceptDate.setText(deliveryDateNew);
                reqGrouponList();

            }
        } else if (resultCode == RESULT_OK && requestCode == 0x1993) {
            if (data != null && mGrouponInfo != null) {
                String ais = data.getStringExtra("agencyItem");
                String id = null;
                String idNew = null;

                if (agencyListItem != null) {
                    id = agencyListItem.getId();
                }
                updateAgencyData(ais);
                if (agencyListItem != null) {
                    idNew = agencyListItem.getId();
                }

                updateAgency(agencyListItem);
                reqGrouponList();
            }
        }
    }

    public void updateAgency(AgencyListItem agencyListItem) {
        if (agencyListItem != null) {
            tvSelectAgentName.setText(agencyListItem.getConsigneeName() + "  " + agencyListItem.getConsigneePhone());
            tvSelectAgentAddress.setText(agencyListItem.getConsigneeAddress());
            tvSelectStoreName.setText(agencyListItem.getName());
        }
    }

    List<GrouponListItem> grouponListCurrent;

    void updateGroupInfo() {
        updateRecommendView(false);
        vhItem0.setItemViewVisible(false);
        vhItem1.setItemViewVisible(false);
        vhItem2.setItemViewVisible(false);
        if (mGrouponList != null) {
            List<GrouponListItem> nextList = mGrouponList.getNextList();
            grouponListCurrent = nextList;
            updateReCommendItem(nextList);
        }

        updateRecommendBtn((mGrouponList != null && mGrouponList.getGrouponListSize() > 3 )? true : false);
    }

    private void updateReCommendItem(List<GrouponListItem> nextList) {
        if (nextList != null) {
            int size = nextList.size();
            if (size == 1) {
                updateRecommendView(true);
                vhItem0.setItemViewVisible(true);
                vhItem0.setData(nextList.get(0));
            } else if (size == 2) {
                updateRecommendView(true);
                vhItem0.setItemViewVisible(true);
                vhItem1.setItemViewVisible(true);
                vhItem0.setData(nextList.get(0));
                vhItem1.setData(nextList.get(1));
            } else if (size > 2) {
                updateRecommendView(true);
                vhItem0.setItemViewVisible(true);
                vhItem1.setItemViewVisible(true);
                vhItem2.setItemViewVisible(true);
                vhItem0.setData(nextList.get(0));
                vhItem1.setData(nextList.get(1));
                vhItem2.setData(nextList.get(2));
            }
        }
    }

    static class ViewHolder {

        View itemView;
        TextView tvAddress1;
        TextView tvAddress2;
        TextView tvDeliveryDate;
        TextView tvLimitAmount;
        TextView tvAmount;
        TextView tvAgent;
        TextView tvMatch;
        ImageView ivSelect;

        ViewHolder(View itemView) {
            this.itemView = itemView;
            tvAddress1 = itemView.findViewById(R.id.tv_address_1);
            tvAddress2 = itemView.findViewById(R.id.tv_address_2);
            tvDeliveryDate = itemView.findViewById(R.id.tv_delivery_date);
            tvLimitAmount = itemView.findViewById(R.id.tv_limit_amount);
            tvAmount = itemView.findViewById(R.id.tv_amount);
            tvAgent = itemView.findViewById(R.id.tv_agent);
            tvMatch = itemView.findViewById(R.id.tv_match);
            ivSelect = itemView.findViewById(R.id.iv_select);

        }

        void setItemViewVisible(boolean isVisible) {
            if (itemView != null) {
                itemView.setVisibility(isVisible ? View.VISIBLE : View.GONE);
            }
        }

        void setData(GrouponListItem post) {

            tvAddress1.setText(post.getBaseCityName());
            tvAddress2.setText(post.getAgencyCityName());
            tvDeliveryDate.setText("预计 " + post.getDeliverTime() + " 发货");
            tvAgent.setText("代办：" + post.getAgencyConsigneeAddress());

            String chargeUnit = post.getChargeUnit();
            String s = "满" + FormatUtil.subZeroAndDot(post.getCountLower()) + chargeUnit + "发货，可拼" + FormatUtil.subZeroAndDot(post.getCountUpper()) + chargeUnit;
            tvLimitAmount.setText(s);
            s = "已拼" + FormatUtil.subZeroAndDot(post.getSumProductCount()) + chargeUnit + "（还剩：" + FormatUtil.subZeroAndDot(post.getRemainCount()) + chargeUnit + "）";
            tvAmount.setText(s);

            if (!post.isSelected()) {
                ivSelect.setImageResource(R.mipmap.register_unread);
            } else {
                ivSelect.setImageResource(R.mipmap.register_read);

            }

            tvMatch.setText(post.getMatchWord());

            ivSelect.setTag(post);
        }
    }

    private void updateView() {

        if (mGrouponInfo != null) {
            updateBottomPrice();
            setData(mGrouponInfo);
            updateAgency(agencyListItem);
        }
    }


    void updateBottomPrice() {
        if (mGrouponInfo != null) {
            String count = mGrouponInfo.getProductCount();
            String freightUnit = mGrouponInfo.getFreightUnit();
            String unitPrice = FormatUtil.subZeroAndDot(mGrouponInfo.getUnitPrice());

            double cost = FormatUtil.countMultiply(count, unitPrice);
            double freight = FormatUtil.countMultiply(freightUnit, count);
//        double total = FormatUtil.countAdd(cost,freight);
            tvTotalCost.setText("共" + FormatUtil.subZeroAndDot(cost) + "元");
            tvFreightCost.setText("另需预计运费" + FormatUtil.subZeroAndDot(freight) + "元");
        } else {
            tvTotalCost.setText("");
            tvFreightCost.setText("");
        }
    }


    private void reqGroupon(String grouponId, String productId) {
        RequestEntityMap data = new RequestEntityMap();
        data.setCmd("pm-order/baseorder/order/load");
        data.setClientIdentifierCode(getAppApplication().getClientIdentifierCode());

        data.putParameter("buyerStoreId", BaseApplication.getInstance().getStoreId());
        data.putParameter("grouponId", grouponId);
        data.putParameter("productId", productId);


        request(data, "pm-order/baseorder/order/load", new OnRequestListener<GrouponInfo>() {
            @Override
            public GrouponInfo jsonToObj(String responseStr) {
                return new Gson().fromJson(responseStr, GrouponInfo.class);
            }

            @Override
            public void onFail(int failCode, Object arg, Object tag) {
                showExceptionView(R.mipmap.icon_error, "请求失败", HttpRequest.FAIL_NET_FAULT);
            }

            @Override
            public void onResponseError(int failCode, Object arg, Object tag) {

                showExceptionView(R.mipmap.icon_error, arg + "", HttpRequest.FAIL_NET_FAULT);
            }

            @Override
            public void onStart(Object tag) {

                showProgressView();
            }

            @Override
            public void onResponse(ResponseEntity<GrouponInfo> response, Object tag) {
                showMainView();
                mGrouponInfo = response.getResponseElement();
                if (!TextUtils.isEmpty(zanting)) {
                    agencyListItem = response.getResponseElement().getAgent();
                }
                if (mGrouponInfo != null) {
                    mGrouponInfo.init();
                }
                updateView();
                reqGrouponList();
            }
        });
    }

    private void reqGrouponList() {
       /* {
            "buyerStoreId": 1,
                "grouponId": 1,
                "productId": 1,
                "buyerStoreId": 1,
                "agencyStoreId": 1,
                "productCount": 1,
                "expectedDeliverTime": "2018-01-01"
        }*/

        if (agencyListItem == null || mGrouponInfo == null) {
            return;
        }
        RequestEntityMap data = new RequestEntityMap();
        data.setCmd("pm-order/baseorder/order/loadgroupon");
        data.setClientIdentifierCode(getAppApplication().getClientIdentifierCode());

        data.putParameter("buyerStoreId", BaseApplication.getInstance().getStoreId());
        data.putParameter("grouponId", grouponId);
        data.putParameter("productId", productId);
        data.putParameter("agencyStoreId", agencyListItem.getId());
//        data.putParameter("productCount", etAmount.getText().toString());
        String s = tvExceptDate.getText().toString();
        if (s != null) {
            s = s.replace("年", "-");
            s = s.replace("月", "-");
            s = s.replace("日", "");
        }
        data.putParameter("expectedDeliverTime", s);

       /* buyerStoreId	是	批发商店铺id
        grouponId	否	拼货单id，和商品id二选一
        productId	否	商品id，和拼货单id二选一
        buyerStoreId	是	当前店铺id
        agencyStoreId	否	上面选择的代办店铺id
        productCount	否	上面输入的数量
        expectedDeliverTime	否	上面选择的期望发货日期*/

        request(data, "pm-order/baseorder/order/loadgroupon", new OnRequestListener<GrouponList>() {
            @Override
            public GrouponList jsonToObj(String responseStr) {
                return new Gson().fromJson(responseStr, GrouponList.class);
            }

            @Override
            public void onFail(int failCode, Object arg, Object tag) {

            }

            @Override
            public void onResponseError(int failCode, Object arg, Object tag) {

            }

            @Override
            public void onStart(Object tag) {

            }

            @Override
            public void onResponse(ResponseEntity<GrouponList> response, Object tag) {
                mGrouponList = response.getResponseElement();
                updateGroupInfo();
            }
        });
    }

    private void reqGrouponSave() {

       /* buyerStoreId	是	批发商店铺id
        grouponId	否	拼货单id，和商品id二选一
        productId	否	商品id，和拼货单iid二选一
        productCount	是	商品数量
        agencyStoreId	是	代办店铺id
        productPriceUnit	是	商品单价
        expectedDeliverDate	是	期望发货时间*/

        if (mGrouponInfo == null && agencyListItem == null) {
            return;
        }

        RequestEntityMap data = new RequestEntityMap();
        data.setCmd("pm-order/baseorder/order/save");
        data.setClientIdentifierCode(getAppApplication().getClientIdentifierCode());

        data.putParameter("buyerStoreId", BaseApplication.getInstance().getStoreId());
        data.putParameter("storeId", storeId);
        data.putParameter("grouponId", grouponId);
        data.putParameter("productId", productId);
        data.putParameter("productCount", mGrouponInfo.getProductCount());
        data.putParameter("cityCode",agencyListItem.getCityId());
        data.putParameter("agencyStoreId", agencyListItem.getId());
        data.putParameter("productPriceUnit", mGrouponInfo.getUnitPrice());
        data.putParameter("expectedDeliverDate", mGrouponInfo.getDeliveryDate());

        request(data, "pm-order/baseorder/order/loadgroupon", new OnRequestListener<PayPreInfo>() {
            @Override
            public PayPreInfo jsonToObj(String responseStr) {
                return JsonUtils.fromJson(responseStr, PayPreInfo.class);
            }

            @Override
            public void onFail(int failCode, Object arg, Object tag) {
                hideProgressDialog();
            }

            @Override
            public void onResponseError(int failCode, Object arg, Object tag) {
                hideProgressDialog();
            }

            @Override
            public void onStart(Object tag) {

                showProgressDialog();
            }

            @Override
            public void onResponse(ResponseEntity<PayPreInfo> response, Object tag) {
                hideProgressDialog();
               /*{
                "requiredProductPayFirst" : 0.01,
                    "payFirstCountDown" : 1800,
                    "orderId" : 131
                }*/

                if (response != null) {
                    PayPreInfo payPreInfo = response.getResponseElement();
                    if (payPreInfo != null) {

                        intoPay(payPreInfo.getRequiredProductPayFirst(), payPreInfo.getPayFirstCountDown(), payPreInfo.getOrderId());
                    }
                }
            }
        });
    }

}
